#pragma once

#include <iostream>
#include <unordered_map>
#include <functional>
#include <ctime>
#include <unistd.h>
#include <sys/types.h>
using task_t = std::function<void()>; 

void DownLoad()
{
    std::cout << "我是下载任务...,pid: " << getpid() << std::endl;
}
void Log()
{
    std::cout << "我是日志任务...,pid: " << getpid() << std::endl;
    //std::cout << "我是日志任务..." << std::endl;
}

void Sql()
{
    std::cout << "我是数据库同步任务...,pid: " << getpid() << std::endl;
    //std::cout << "我是数据库同步任务..." << std::endl;
}
static int number = 0; 
class TaskManager
{
public:
    TaskManager()
    {
        srand(time(nullptr));
        InsertTask(DownLoad);
        InsertTask(Log);
        InsertTask(Sql);
    }
     
    void InsertTask(task_t t)
    {
        tasks[number++] = t;
    }
    int SelectTask()
    {
        return rand() % number;
    }
    void Exceute(int number)
    {
        if(!tasks.count(number)) return;
        tasks[number]();
    }
    ~TaskManager()
    {}
private:
    std::unordered_map<int,task_t> tasks;
};

TaskManager tm;//单例模式   

void Worker()
{
    while(true)
    {
        int cmd = 0;
        int n = ::read(0, &cmd, sizeof(cmd));//读一个整数，所有子进程在这阻塞
        if(n == sizeof(cmd))
        {
            tm.Exceute(cmd);//根据任务码，执行任务
        }
        else if(n == 0)//表示管道写端关闭
        {
            std::cout<< "pid: " << getpid() <<"quit..." << std::endl;
            break;
        }
        else
        {}
    }
}